package com.jy.adscm.operation.mscyb.service.impl;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jy.adscm.bean.system.JyUser;
import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.operation.cg.bean.CgBom;
import com.jy.adscm.operation.cg.bean.CgMaterial;
import com.jy.adscm.operation.cg.mapper.mysql.CgBomMapper;
import com.jy.adscm.operation.cg.mapper.mysql.CgMaterialMapper;
import com.jy.adscm.operation.mscyb.bean.*;
import com.jy.adscm.operation.mscyb.controller.JqzzMachineController;
import com.jy.adscm.operation.mscyb.mapper.mysql.*;
import com.jy.adscm.operation.mscyb.service.JqylMaterialService;
import com.jy.adscm.operation.mscyb.service.JqzzMaterialListService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jy.adscm.operation.purchase.bean.Purchasebom;
import com.jy.adscm.operation.purchase.mapper.mysql.PurchasebomMapper;
import com.jy.adscm.security.utils.Token;
import com.jy.adscm.system.mapper.mysql.JyUserMapper;
import com.jy.adscm.utils.AdscmBaseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zyl
 * @since 2019-06-02
 */
@Service
public class JqzzMaterialListServiceImpl extends ServiceImpl<JqzzMaterialListMapper, JqzzMaterialList> implements JqzzMaterialListService {
    @Autowired
    JqylMaterialService  jqylMaterialService;
    @Autowired
    JqylMaterialMapper jqylMaterialMapper;
    @Autowired
    CgMaterialMapper CgMaterialMapper;
    @Autowired
    JqzzMaterialMapper jqzzMaterialMapper;
    @Autowired
    JqylMaterialdetailMapper jqylMaterialdetailMapper;
    @Autowired
    JqzzMaterialListCheckMapper jqzzMaterialListCheckMapper;
    @Autowired
    JqzzMachineMapper jqzzMachineMapper;
    @Autowired
    JyUserMapper jyUserMapper;
    @Autowired
    JqylSettingMaterialCheckMapper jqylSettingMaterialCheckMapper;
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean insertJqzzMaterialList(JqzzMaterialList jqzzMaterialList, Token token) throws AdscmSystemException {
        float temp=  jqzzMaterialList.getNum();
        int num= (int)temp ;
        boolean isInt=true;
        if (temp==num){

        }else {
            num=1;
            isInt=false;
        }
        for (int i = 0; i < num; i++) {
            if (isInt){
                jqzzMaterialList.setNum(1f);
            }else {
                jqzzMaterialList.setNum(temp);
            }
            //根据这个查询原来库存中是否还存在余料
            if (AdscmBaseUtils.getInstance().isNotEmpty(jqzzMaterialList.getName(), null)) {

                //修改库存  减去库存  num相反数
                JqylMaterial jqylMaterial = jqylMaterialService.updateJqylMaterialyValue(jqzzMaterialList.getName(), jqzzMaterialList.getNum()*-1);

                //根据任务书中的物料名称获取到物料的编码
                CgMaterial cgMaterial = CgMaterialMapper.selectById(jqylMaterial.getResourcename());
                if (!AdscmBaseUtils.getInstance().isNotEmpty(cgMaterial,null)){
                    throw new AdscmSystemException("找不到该物料编码:"+cgMaterial.getName());
                }

                if (AdscmBaseUtils.getInstance().isNotEmpty(cgMaterial.getType(),null)){
                    jqzzMaterialList.setType(cgMaterial.getType());
                }
                if (AdscmBaseUtils.getInstance().isNotEmpty(jqylMaterial.getBatchnums(),null)){
                    jqzzMaterialList.setBatch(jqylMaterial.getBatchnums());
                }
                if (AdscmBaseUtils.getInstance().isNotEmpty(cgMaterial.getCode(),null)){
                    String yearMonth = new SimpleDateFormat("yyMMdd").format(new Date());
                    String code=cgMaterial.getCode().trim()+yearMonth;
                    Wrapper<JqzzMaterialList> wrapper =new EntityWrapper<>();
                    wrapper.like("code",code, SqlLike.RIGHT);
                    wrapper.orderBy("code",false);
                    List<JqzzMaterialList> jqzzMaterialLists = super.selectList(wrapper);
                    if (jqzzMaterialLists!=null && jqzzMaterialLists.size()>0){
                        JqzzMaterialList JqzzMaterialList1 = jqzzMaterialLists.get(0);
                        code=JqzzMaterialList1.getCode().replace(cgMaterial.getCode().trim(),"");
                        Long tempcode= Long.valueOf(code)+1;
                        jqzzMaterialList.setCode(cgMaterial.getCode().trim()+String.valueOf(tempcode));
                    }else {
                        jqzzMaterialList.setCode(cgMaterial.getCode().trim()+yearMonth+"001");
                    }
                }
                //添加用料信息
                jqzzMaterialList.setCreateTime(new Date());
                jqzzMaterialList.setCreator(token.getUser().getId().toString());
                jqzzMaterialList.setState(1);
                //默认使用时间为当前
                jqzzMaterialList.setUseTime(new Date());
                super.insert(jqzzMaterialList);

                //如果提交的数量和计划的数量相等，默认已经完成领料
                JqzzMaterial jqzzMaterial = jqzzMaterialMapper.selectById(jqzzMaterialList.getPid());
                Wrapper<JqzzMaterialList> getAllWrapper=new EntityWrapper<>();
                getAllWrapper.eq("pid",jqzzMaterial.getId());
                getAllWrapper.eq("state","1");
                List<JqzzMaterialList> jqzzMaterialLists = super.selectList(getAllWrapper);
                float tempNum=0;
                    for (JqzzMaterialList materialList : jqzzMaterialLists) {
                        tempNum=tempNum+materialList.getNum();
                    }
                if (jqzzMaterial.getNum()<tempNum){
                    throw  new AdscmSystemException("添加数量大于了需求数量"+cgMaterial.getName());
                }
                if (jqzzMaterial.getNum()==tempNum){
                    jqzzMaterial.setIsAssembly(1);
                    jqzzMaterialMapper.updateById(jqzzMaterial);
                }else {
                    jqzzMaterial.setIsAssembly(0);
                    jqzzMaterialMapper.updateById(jqzzMaterial);
                }
                //出库信息
                JqylMaterialdetail jqylMaterialdetail=new JqylMaterialdetail();
                jqylMaterialdetail.setName(jqylMaterial.getResourcename());
                jqylMaterialdetail.setTypenums(jqylMaterial.getTypenums());
                jqylMaterialdetail.setUnit(jqylMaterial.getUnit());
                jqylMaterialdetail.setBatchnums(jqylMaterial.getBatchnums());
                JqzzMachine jqzzMachine = jqzzMachineMapper.selectById(jqzzMaterial.getTid());
                if (AdscmBaseUtils.getInstance().isNotEmpty(jqzzMachine,null)){
                    jqylMaterialdetail.setMcode(jqzzMachine.getTaskcode());
                }

                jqylMaterialdetail.setOutstorageaddtime(new Date());
                if (AdscmBaseUtils.getInstance().isNotEmpty(token,null)){
                    jqylMaterialdetail.setUseperson(token.getUser().getId().toString());
                }else {
                    throw  new AdscmSystemException("请重新登录");
                }
                jqylMaterialdetail.setIsrepair(0);
                jqylMaterialdetail.setUsenums( Double.valueOf(jqzzMaterialList.getNum()) );
                jqylMaterialdetail.setMaterialstate(jqzzMaterialList.getState().toString());
                jqylMaterialdetail.setMid(jqzzMaterialList.getId().toString());
                jqylMaterialdetail.setOutstoragetime(jqzzMaterialList.getUseTime());
                jqylMaterialdetail.setTid(jqylMaterial.getTid().toString());
                jqylMaterialdetail.setCode(jqzzMaterialList.getCode());
                jqylMaterialdetail.setMaterialstate("1");
                jqylMaterialdetailMapper.insert(jqylMaterialdetail);
                //生成检验记录
                Wrapper<JqylSettingMaterialCheck> wrapper =new EntityWrapper<>();
                wrapper.eq("pid",cgMaterial.getId());
                wrapper.eq("isEnable",1);

                List<JqylSettingMaterialCheck> jqylSettingMaterialChecks = jqylSettingMaterialCheckMapper.selectList(wrapper);

                if (jqylSettingMaterialChecks!=null && jqylSettingMaterialChecks.size()>0 ){
                    for (JqylSettingMaterialCheck jqylSettingMaterialCheck : jqylSettingMaterialChecks) {
                        JqzzMaterialListCheck  jqzzMaterialListCheck =new JqzzMaterialListCheck();
                        jqzzMaterialListCheck.setPid(jqzzMaterialList.getId());
                        jqzzMaterialListCheck.setCid(jqylSettingMaterialCheck.getId());
                        jqzzMaterialListCheck.setName(jqylSettingMaterialCheck.getName());
                        jqzzMaterialListCheck.setReference(jqylSettingMaterialCheck.getReference());
                        jqzzMaterialListCheck.setType(jqylSettingMaterialCheck.getType());
                        jqzzMaterialListCheck.setUnit(jqylSettingMaterialCheck.getUnit());
                        jqzzMaterialListCheck.setRemark(jqylSettingMaterialCheck.getRemark());
                        jqzzMaterialListCheck.setRank(jqylSettingMaterialCheck.getRank());
                        jqzzMaterialListCheckMapper.insert(jqzzMaterialListCheck);
                    }
                    jqzzMaterialList.setIsCheck(1);
                }else {
                    jqzzMaterialList.setIsCheck(0);
                    jqzzMaterialList.setState(1);
                }
                super.updateById(jqzzMaterialList);
            }


        }


        return false;
    }
    @Transactional
    @Override
    public boolean deleteJqzzMaterialList(Integer id) throws AdscmSystemException {
        //1.查询出该条记录
        JqzzMaterialList jqzzMaterialList = super.selectById(id);
        //2.修改回原来的库存
        jqylMaterialService.updateJqylMaterialyValue(jqzzMaterialList.getName(), jqzzMaterialList.getNum());
        ///3.删除掉对应的库存出库记录
        Wrapper<JqylMaterialdetail> wrapper =new EntityWrapper<>();
        wrapper.eq("MID",id);
        List<JqylMaterialdetail> jqylMaterialdetails = jqylMaterialdetailMapper.selectList(wrapper);
        if (jqylMaterialdetails!=null&& jqylMaterialdetails.size()>0){
            JqylMaterialdetail jqylMaterialdetail = jqylMaterialdetails.get(0);
            jqylMaterialdetailMapper.deleteById(jqylMaterialdetail.getId());
        }
        //删除对应的检验记录
        Wrapper<JqzzMaterialListCheck> jqzzMaterialListCheckwrapper=new EntityWrapper<>();
        jqzzMaterialListCheckwrapper.eq("pid",id);
        List<JqzzMaterialListCheck> jqzzMaterialListChecks = jqzzMaterialListCheckMapper.selectList(jqzzMaterialListCheckwrapper);
        if (jqzzMaterialListChecks!=null && jqzzMaterialListChecks.size()>0){
            JqzzMaterialListCheck jqzzMaterialListCheck = jqzzMaterialListChecks.get(0);
            jqzzMaterialListCheckMapper.deleteById(jqzzMaterialListCheck);
        }
        //修改父级装配状态
        JqzzMaterial jqzzMaterial = jqzzMaterialMapper.selectById(jqzzMaterialList.getPid());
        jqzzMaterial.setIsAssembly(0);
        jqzzMaterialMapper.updateById(jqzzMaterial);
        boolean b = super.deleteById(id);
        return b;
    }
    @Transactional
    @Override
    public boolean updateJqzzMaterrialList(JqzzMaterialList jqzzMaterialList) throws AdscmSystemException {
        if (AdscmBaseUtils.getInstance().isNotEmpty(jqzzMaterialList.getCode(),null)){
            if (jqzzMaterialList.getNum()>1){
                throw  new AdscmSystemException("无法修改数量");
            }
        }
        Wrapper<JqylMaterialdetail> wrapper =new EntityWrapper<>();
        wrapper.eq("MID",jqzzMaterialList.getId());
        List<JqylMaterialdetail> jqylMaterialdetails = jqylMaterialdetailMapper.selectList(wrapper);
        JqylMaterialdetail jqylMaterialdetail =null;
        if (jqylMaterialdetails!=null &&jqylMaterialdetails.size()>0){
            jqylMaterialdetail=jqylMaterialdetails.get(0);
        }
//        JqbzMaterialList oldjqzzMaterialList = super.selectById(jqzzMaterialList.getId());
//        Integer num=  oldjqzzMaterialList.getNum()-jqzzMaterialList.getNum();
//        //数量有变化修改原料库  库存
//        if (num!=0){
//            jqylMaterialService.updateJqylMaterialyValue(jqzzMaterialList.getName(), num);
//        }
        //修改原料的出库记录 数量和状态
        jqylMaterialdetail.setMaterialstate(jqzzMaterialList.getState().toString());
       // jqylMaterialdetail.setUsenums(Double.valueOf(jqzzMaterialList.getNum().toString()));
        jqylMaterialdetailMapper.updateById(jqylMaterialdetail);

        boolean b = super.updateById(jqzzMaterialList);
        return b;
    }

    @Override
    public List<JqzzMaterialList> selectByTid(String tid) throws AdscmSystemException {
        Wrapper<JqzzMaterialList> wrapper =new EntityWrapper<>();
        wrapper.eq("pid",tid);
        List<JqzzMaterialList> jqzzMaterialLists = super.selectList(wrapper);
        for (JqzzMaterialList jqzzMaterialList : jqzzMaterialLists) {
            if (AdscmBaseUtils.getInstance().isNotEmpty(jqzzMaterialList.getName(),null)){
                JqylMaterial jqylMaterial = jqylMaterialMapper.selectById(Integer.valueOf(jqzzMaterialList.getName()));
                CgMaterial cgMaterial = CgMaterialMapper.selectById(Integer.valueOf(jqylMaterial.getResourcename()));
                if (AdscmBaseUtils.getInstance().isNotEmpty(cgMaterial,null)){
                    jqzzMaterialList.setNameName(cgMaterial.getName());
                }
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(jqzzMaterialList.getCreator(),null)){
                JyUser jyUser = jyUserMapper.selectById(jqzzMaterialList.getCreator());
                if (AdscmBaseUtils.getInstance().isNotEmpty(jyUser,null)){
                    jqzzMaterialList.setCreatorName(jyUser.getName());
                }
            }

        }
        return jqzzMaterialLists;
    }

    @Override
    public List<JqylMaterial> queryMaterial(String id) throws AdscmSystemException {
        Wrapper<JqylMaterial> wrapper =new EntityWrapper<>();
        wrapper.setSqlSelect("TID","RESOURCENAME","TASKCODE","REMAININGNUMS");
        wrapper.eq("ISTASKBEGIN",1);
        wrapper.eq("ISTASKEND",0);
        wrapper.eq("RESOURCENAME",id);
        List<JqylMaterial> jqylMaterials = jqylMaterialMapper.selectList(wrapper);
        if(!(jqylMaterials!=null&&jqylMaterials.size()>0)){
            throw new AdscmSystemException("原料库中无存货");
        }
        for (JqylMaterial jqylMaterial : jqylMaterials) {
            if (AdscmBaseUtils.getInstance().isNotEmpty(jqylMaterial.getResourcename(),null)){
                CgMaterial cgMaterial = CgMaterialMapper.selectById(jqylMaterial.getResourcename());
                jqylMaterial.setCgMaterial(cgMaterial);
            }
        }

        return jqylMaterials;
    }

    @Override
    public boolean updateJqzzMaterialList(JqzzMaterialList jqzzMaterialList)throws AdscmSystemException {
        if (AdscmBaseUtils.getInstance().isNotEmpty(jqzzMaterialList.getCode(),null)){
            if (jqzzMaterialList.getNum()>1){
                throw  new AdscmSystemException("无法修改数量");
            }
        }
        Wrapper<JqylMaterialdetail> wrapper =new EntityWrapper<>();
        wrapper.eq("pid",jqzzMaterialList.getId());
        List<JqylMaterialdetail> jqylMaterialdetails = jqylMaterialdetailMapper.selectList(wrapper);
        JqylMaterialdetail jqylMaterialdetail =null;
        if (jqylMaterialdetails!=null &&jqylMaterialdetails.size()>0){
            jqylMaterialdetail=jqylMaterialdetails.get(0);
        }
        JqzzMaterialList oldjqzzMaterialList = super.selectById(jqzzMaterialList.getId());
        Float num=  oldjqzzMaterialList.getNum()-jqzzMaterialList.getNum();
        //数量有变化修改原料库  库存
        if (num!=0){
            jqylMaterialService.updateJqylMaterialyValue(jqzzMaterialList.getName(), num);
        }
        //修改原料的出库记录 数量和状态
        jqylMaterialdetail.setMaterialstate(jqzzMaterialList.getState().toString());
        jqylMaterialdetail.setUsenums(Double.valueOf(jqzzMaterialList.getNum().toString()));
        jqylMaterialdetailMapper.updateById(jqylMaterialdetail);
        boolean b = super.updateById(jqzzMaterialList);
        return b;
    }
}
